#!/usr/bin/env bash
# vim: fdm=marker fmr=[[[,]]] cms=\ #%s

usage()
{ #[[[
    echo "Usage: $(basename $0) [-t mp3|ogg] file(ape|flac)"
} #]]]

main()
{ #[[[
    while getopts 't:' opt
    do
        case $opt in
            t)
                target=$OPTARG
                case $target in
                    mp3)
                        target_cmd="lame --preset extreme -"
                        ;;
                    ogg)
                        target_cmd="oggenc -q 8 - -o"
                        ;;
                    *)
                        usage
                        return
                        ;;
                esac
                ;;
            *)
                usage
                return
                ;;
        esac
    done
    if [[ -z $target ]]
    then
        target=mp3
        target_cmd="lame --preset extreme -"
    fi

    shift $(($OPTIND-1))
    if [[ $# == 0 ]]
    then
        usage
        return
    fi
    file=$1
    source=${file##*.}
    echo $source
    case $source in
        ape)
            ;;
        flac)
            ;;
        *)
            usage
            return
            ;;
    esac

    filename=${file%.*}
    echo "file:{$file} filename:{$filename}"
    echo "source:{$source} target:{$target} target_cmd:{$target_cmd}"
    if [[ ! -r "${filename}.cue" ]]
    then
        echo "${filename}.cue not found"
        return
    fi

    iconv -f gbk -t utf-8 "$filename.cue" > tmp.cue
    echo "cust ext=$target $target_cmd - %f" "$file"
#    shnsplit -f tmp.cue -i $source -t "%n.%t-%p" -o "cust ext=$target $target_cmd %f" "$file"
    shnsplit -f tmp.cue -i $source -t "%n.%t" -o "cust ext=$target $target_cmd %f" "$file"
} #]]]

main "$@"
